﻿<script lang="ts" setup>
import type { VNodeRef } from 'vue'
import { ref, reactive, onMounted, onBeforeUpdate } from 'vue'
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import {
  TreeSelectProps,
  CascaderProps,
  SelectProps,
  Empty
} from 'ant-design-vue'
import type { DefaultOptionType } from 'ant-design-vue/lib/vc-cascader'
import { MaintenanceRecordEditType } from '@/types/modules/maintenance-record'
import useCol from '@/hooks/system/useCol'
import { useI18n } from '@/hooks/web/useI18n'
import { Status } from '@/utils/http/types.d'
import * as api from '@/api/modules/maintenance-record'

const { t } = useI18n()

const props = defineProps({
  rank: { type: Number },
  isItem: { type: Boolean, default: false },
  isList: { type: Boolean, default: false },
  itemData: {
    type: Object as PropType<MaintenanceRecordEditType>,
    default: () => ({
      description: undefined,
      overhauler: undefined,
      phone: undefined,
      repairDate: undefined,
    })
  }
})

const { getBindCol } = useCol(props.isList)

const formRef = ref()
const refs = ref<any[]>([])
const formState = reactive<Expandable<MaintenanceRecordEditType>>(props.itemData)

const basicRules = {
  description: [
    { min: 15, message: '描述信息不少于15个字。', trigger: 'blur' },
  ],
  phone: [
    {
      pattern: /^(0|86)?(13[0-9]|15[0-35-9]|17[013678]|18[0-9]|14[57])\d{8}$/,
      message: '手机号码格式不正确。',
      trigger: 'blur'
    },
  ],
}

onBeforeUpdate(() => {
  refs.value = []
})

const setItemRef = (el: VNodeRef): VNodeRef => {
  if (el) {
    refs.value.push(el)
  }
  return el
}

const filterCascaderOptions = (inputValue: string, path: DefaultOptionType[]) =>
  path.some(
    option =>
      (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) >
      -1
  )

const handleBasicOk = async () => {
  let valid = await formRef.value.validate().catch((err: any) => err)
  if (!valid?.errorFields?.length) return valid
  return false
}

const resetBasicForm = () => {
  formRef.value.resetFields()
}

const handleRelateArrOk = async () => {
  let relateArr = []
  let isFailed = false
  for (let i = 0; i < refs.value.length; i++) {
    const result = await (refs.value[i] as any).handleOk()
    relateArr.push(result)
    if (!result) {
      isFailed = true
    }
  }
  if (isFailed) return false
  return relateArr
}

const resetRelateArrForm = () => {
  for (let i = 0; i < refs.value.length; i++) {
    ;(refs.value[i] as any).resetForm()
  }
}

const handleOk = async () => {
  const basicResult = await handleBasicOk()
  const relateArrRsult = await handleRelateArrOk()
  if (basicResult && relateArrRsult) {
    return formState
  }
  return false
}

const resetForm = () => {
  resetBasicForm()
  resetRelateArrForm()
}

const emit = defineEmits(['delete'])
const hanldeDeleteData = () => {
  emit('delete', props.rank)
}

const change = (date, dateString) => {
  console.log(date, dateString);

}

defineExpose({ handleOk, resetForm })
</script>
<template>
  <div :class="['form-container', { isChild: isItem }]">
    <div class="form-wrapper">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="basicRules"
        :labelWrap="true"
        @finish="handleOk"
      >
        <a-form-item name="description" label="描述" v-bind="getBindCol">
          <a-input
            v-model:value="formState['description']"
            :placeholder="`描述`"
            allow-clear
          />
        </a-form-item>
        <a-form-item name="overhauler" label="检修人" v-bind="getBindCol">
          <a-input
            v-model:value="formState['overhauler']"
            :placeholder="`检修人`"
            allow-clear
          />
        </a-form-item>
        <a-form-item name="phone" label="联系方式" v-bind="getBindCol">
          <a-input
            v-model:value="formState['phone']"
            :placeholder="`联系方式`"
            allow-clear
          />
        </a-form-item>
        <a-form-item name="repairDate" label="维修日期" v-bind="getBindCol">
          <a-date-picker
            v-model:value="formState['repairDate']"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="维修日期"
            show-time
            allow-clear
          />
        </a-form-item>
      </a-form>
    </div>
    <div v-if="isItem" class="del">
      <a-popconfirm
        :title="t('system.deletePrompt')"
        placement="top"
        @confirm="hanldeDeleteData"
      >
        <delete-outlined :style="{ fontSize: '16px', color: '#f00' }" />
      </a-popconfirm>
    </div>
  </div>
</template>

<style lang="less" scoped>
.form-container {
  &.isChild {
    margin: 0;
    border: 1px solid @border-color-base;
    padding-top: 18px;
    border-radius: 4px;
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .del {
      margin: 0 20px;
      cursor: pointer;
    }

    .form-wrapper {
      flex-grow: 2;
    }
  }
}

.ant-picker,
.ant-input-number {
  width: 100%;
}
</style>
